package com.hmdp.utils;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.hmdp.dto.UserDTO;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class RefreshInterceptor implements HandlerInterceptor {

    //这个类不是由spring创建的对象，所以不能依赖注入，比如加个@Resource
    //所以需要在使用这个方法的类中用构造函数来注入
    StringRedisTemplate stringRedisTemplate;

    public RefreshInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //1.获取请求头的token
        String token = request.getHeader("authorization");


        if (StrUtil.isBlank(token)) {

            return true;
        }

        String key = RedisConstants.LOGIN_USER_KEY + token;
        //2.基于token获取redis中的用户  entries()获取所有的键值对
        Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries(key);

        //3.判断用户是否存在 isEmpty() 判断集合是否为空
        if (userMap.isEmpty()   ) {
            //4.不存在 拦截
            return true;
        }
        //5.将查询到的userMap转化为DTO对象 ,第一个参数是要转化的集合，第二个是用哪个bean,第三个参数是否忽略转换中的错误，

        UserDTO userDTO = BeanUtil.fillBeanWithMap(userMap, new UserDTO(), false);

        //6.保存用户信息到Threadlocal中 方便其他地方拿取user信息
        UserHolder.saveUser(userDTO);

        //7.刷新token有效期
        stringRedisTemplate.expire(key,RedisConstants.LOGIN_USER_TTL, TimeUnit.MINUTES);

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
